package com.example.websockettest.webSocket.回收站;

import javax.sound.sampled.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import static com.example.websockettest.webSocket.回收站.VoiceRecognition.*;

public class AudioRecorder {
    private static final int SAMPLE_RATE = 16000;
    private static final int SAMPLE_SIZE_IN_BITS = 16;
    private static final int CHANNELS = 1;
    private static final boolean SIGNED = true;
    private static final boolean BIG_ENDIAN = true;

    private TargetDataLine line;
    private ByteArrayOutputStream out;

    public void start() throws LineUnavailableException {
        AudioFormat format = new AudioFormat(SAMPLE_RATE, SAMPLE_SIZE_IN_BITS, CHANNELS, SIGNED, BIG_ENDIAN);
        line = AudioSystem.getTargetDataLine(format);
        line.open(format);
        line.start();
        out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        while (true) {
            int bytesRead = line.read(buffer, 0, buffer.length);
            out.write(buffer, 0, bytesRead);
            byte[] audioData = out.toByteArray();
            String text = new ASRClient(APP_ID, API_KEY, SECRET_KEY).recognize(audioData);
            if (text != null) {
                System.out.println(text);
                out.reset();
            }
        }
    }

    public void stop() throws IOException {
        line.stop();
        line.close();
        out.close();
    }
}

